package zhang.lao.console.controller.wn;
import com.alibaba.fastjson.JSON;
import com.google.zxing.WriterException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zhang.lao.annotation.RepeatSubmit;
import zhang.lao.build.kit.ehcache.CacheKit;
import zhang.lao.build.tool.PathKit;
import zhang.lao.build.tool.ZipTool;
import zhang.lao.console.service.MakeNjQrCodeService;
import zhang.lao.pojo.console.ConsoleContext;
import zhang.lao.pojo.console.req.BootStrapGridReq;
import zhang.lao.pojo.console.resp.BootStrapGridResp;
import zhang.lao.pojo.console.resp.HttpResult;
import zhang.lao.pojo.console.resp.HttpResultEnum;
import zhang.lao.pojo.console.resp.HttpResultUtil;
import zhang.lao.service.console.base.WnMachineService;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
* 农机
* @author ZhangQin
* @create 2017年08月28日 17:02
**/
@Controller
public class WnMachineController{
	@Resource
	private WnMachineService wnMachineService;

	@RequestMapping("/console/wn_machine/add")
	@RepeatSubmit(isAdd = true)
	public String add(){
		return wnMachineService.add();
	}

	@RepeatSubmit(isAdd = true)
	@RequestMapping("/console/wn_machine/edit")
	public String edit(ModelMap modelMap,String id){
		return  wnMachineService.edit(modelMap,id);
	}

	@RequestMapping("/console/wn_machine/list")
	public String list(){
		return  wnMachineService.list();
	}

	@RequestMapping("/console/wn_machine/json")
	public @ResponseBody BootStrapGridResp json(BootStrapGridReq bootGridReq, ConsoleContext consoleContext){
		return wnMachineService.json(bootGridReq,consoleContext);
	}

	@RepeatSubmit(isAdd = false)
	@RequestMapping("/console/wn_machine/save")
	public @ResponseBody HttpResult save(String formObjectJson,String appUserId){
		return wnMachineService.save(formObjectJson,appUserId);

	}

	@RequestMapping("/console/wn_machine/delete")
	public @ResponseBody HttpResult delete(String ids){
        return wnMachineService.delete(ids);
	}

	@Resource
	private MakeNjQrCodeService makeNjQrCodeService;
	/**
	 * 生成二维码到输出流
	 */
	@RequestMapping("/console/wn_machine/qrcode/{id}")
	public void getQrCode(HttpServletResponse response, @PathVariable String id){
		String QrcodeContentZj;
		OutputStream outputStream=null;
		try {
			outputStream=response.getOutputStream();
			makeNjQrCodeService.getImageByNjId(id,outputStream);
		} catch (IOException e) {
		} catch (WriterException e) {
		} catch (Exception e) {
		} finally{
			try {
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
			}
		}
	}
	@RequestMapping("/console/wn_machine/qrcode/make")
	public @ResponseBody
	HttpResult makeQrcode(ConsoleContext consoleContext){
		try {
			CacheKit.put("downLoadCache",consoleContext.getUserId(),"run");
			makeNjQrCodeService.makeImage(consoleContext);
			CacheKit.put("downLoadCache",consoleContext.getUserId(),"end");
		} catch (Exception e) {
			e.printStackTrace();
			CacheKit.put("downLoadCache",consoleContext.getUserId(),"end");
		}
		return HttpResultUtil.buildSuccess();
	}

	@RequestMapping("/console/wn_machine/qrcode/make/zip")
	public void downLoadCache(ConsoleContext consoleContext,HttpServletResponse response){
		String state = CacheKit.get("downLoadCache",consoleContext.getUserId());
		if(StringUtils.isNotBlank(state)&&state.equals("end")) {
			File fileZ = new File(PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "file" + File.separator + "njqrcode" + File.separator + consoleContext.getUserId()+".zip");
			if(fileZ.exists()){fileZ.delete();}
			new ZipTool(PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "file" + File.separator + "njqrcode" + File.separator + consoleContext.getUserId()+".zip").compressExe(PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "file" + File.separator + "njqrcode" + File.separator + consoleContext.getUserId());
			File file = new File(PathKit.getWebRootPath() + File.separator + "WEB-INF" + File.separator + "file" + File.separator + "njqrcode" + File.separator + consoleContext.getUserId()+".zip");
			OutputStream stream = null;
			try {
				FileInputStream inputStream = new FileInputStream(file);
				byte[] data = new byte[(int) file.length()];
				inputStream.read(data);
				inputStream.close();
				response.setContentType("application/x-zip-compressed");
				response.addHeader("Content-Disposition", "attachment; filename=" + System.nanoTime()+".zip");
				stream = response.getOutputStream();
				stream.write(data);
			} catch (IOException e) {
			} finally {
				if (stream != null) {
					try {
						stream.close();
					} catch (IOException e) {
					}
				}
			}
		}else{
			PrintWriter writer = null;
			try {
				response.setHeader("Pragma", "no-cache");	// HTTP/1.0 caches might not implement Cache-Control and might only implement Pragma: no-cache
				response.setHeader("Cache-Control", "no-cache");
				response.setDateHeader("Expires", 0);

				response.setContentType("application/json; charset=UTF-8");
				writer = response.getWriter();
				writer.write(JSON.toJSONString(HttpResultUtil.buildError(HttpResultEnum.MAKEQRCODESUBMIT)));
				writer.flush();
			} catch (IOException e) {
			}
			finally {
				if (writer != null)
					writer.close();
			}
		}

	}
}
